package com.weme.main

import android.graphics.drawable.Drawable
import android.os.Bundle
import android.os.Looper
import android.view.KeyEvent
import android.widget.ImageView
import androidx.core.content.ContextCompat
import androidx.core.graphics.BlendModeColorFilterCompat
import androidx.core.graphics.BlendModeCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.ProcessLifecycleOwner
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.alibaba.android.arouter.facade.annotation.Route
import com.jeremyliao.liveeventbus.LiveEventBus
import com.osom.proto.message.Brocast
import com.weme.common.activity.CallActivity
import com.weme.common.activity.CallOperationType
import com.weme.common.arouter.ARouterPaths
import com.weme.common.base.BaseMvvmActivity
import com.weme.common.controller.FloatingWindowController
import com.weme.common.manager.GetGiftListReplyManager
import com.weme.common.manager.MessageHandler.Companion.cancelUid
import com.weme.common.manager.SocketConnectManager
import com.weme.common.network.CallSuspendCancel
import com.weme.common.network.CallsPhone
import com.weme.common.util.AppMkHelper
import com.weme.common.util.JumpUserManager
import com.weme.common.util.LiveConfig
import com.weme.common.util.UserMKHelper
import com.weme.common.util.downloadMp4
import com.weme.common.util.gone
import com.weme.common.util.setVisible
import com.weme.common.util.showToast
import com.weme.common.util.visible
import com.weme.common.util.zoomIn
import com.weme.common.util.zoomOut
import com.weme.common.view.CustomDialogFragment
import com.weme.home.HomeFragment
import com.weme.main.databinding.ActivityMainBinding
import com.weme.main.viewmode.MainViewMode
import com.weme.matching.MatchingFragment
import com.weme.message.MessageFragment
import com.weme.mine.MineFragment
import dev.kratos.api.user_server.v1.GetAccountInfoReply
import dev.kratos.api.user_server.v1.GetCountryListRequest
import dev.kratos.api.user_server.v1.GetGiftListReply
import dev.kratos.api.user_server.v1.GetGiftListRequest
import io.agora.chat.BuildConfig
import io.agora.chat.ChatClient
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch


@Route(path = ARouterPaths.MAIN_ACTIVITY)
class MainActivity : BaseMvvmActivity<ActivityMainBinding, MainViewMode>() {

    private lateinit var matchingFragment: MatchingFragment
    private lateinit var homeFragment: HomeFragment
    private lateinit var messageFragment: MessageFragment
    private lateinit var mineFragment: MineFragment


    private lateinit var matchingDrawable: Drawable
    private lateinit var homeDrawable: Drawable
    private lateinit var messageDrawable: Drawable
    private lateinit var mineDrawable: Drawable
    private var selectColor: Int = 0
    private var unselectColor: Int = 0
    private val lifecycleOwner = ProcessLifecycleOwner.get()

    override fun getViewModelClass(): Class<MainViewMode> = MainViewMode::class.java

    override fun initView(savedInstanceState: Bundle?) {



        JumpUserManager.initialize()
        FloatingWindowController.initialize(this)//初始化小窗
        matchingDrawable = ContextCompat.getDrawable(this, com.example.resources.R.drawable.icon_matching_unselected)!!
        homeDrawable = ContextCompat.getDrawable(this, com.example.resources.R.drawable.icon_home_unselected)!!
        messageDrawable = ContextCompat.getDrawable(this, com.example.resources.R.drawable.icon_message_unselected)!!
        mineDrawable = ContextCompat.getDrawable(this, com.example.resources.R.drawable.icon_mine_unselected)!!

        selectColor = ContextCompat.getColor(this, com.example.resources.R.color.app_btn_colors)
        unselectColor = ContextCompat.getColor(this, com.example.resources.R.color.white)

        matchingDrawable.colorFilter = BlendModeColorFilterCompat.createBlendModeColorFilterCompat(selectColor, BlendModeCompat.SRC_IN)
        mBinding.isMatching.setImageDrawable(matchingDrawable)
        mBinding.isMatching.zoomIn()

     LiveEventBus.get<Int>(LiveConfig.NEW_HOME_INDEX, Int::class.java).observe(this) {
            when (it) {
                0 -> {
                    handleBottomNavigationClick(0, mBinding.isMatching, mBinding.isHome, mBinding.isMessage, mBinding.isMine)
                }
                1 -> {
                    handleBottomNavigationClick(1, mBinding.isMatching, mBinding.isHome, mBinding.isMessage, mBinding.isMine)
                }
                2 -> {
                    handleBottomNavigationClick(2, mBinding.isMatching, mBinding.isHome, mBinding.isMessage, mBinding.isMine)
                }
                3 -> {
                    handleBottomNavigationClick(3, mBinding.isMatching, mBinding.isHome, mBinding.isMessage, mBinding.isMine)
                }
            }
        }
     LiveEventBus.get<Any>(LiveConfig.NET_COSTOM_MSG).observe(this) {
            if (it is CallSuspendCancel) {
                GlobalScope.launch {
                    if (cancelUid != 0L) {
                        viewModel.setCancelCall(it.channelName, cancelUid)
                    }
                }
            }
        }


        if (!AppMkHelper.decodeBoolean(AppMkHelper.COUNTRY_ALL)) {
            viewModel.getCountryList(GetCountryListRequest.newBuilder().setPage(1).setLimit(1000).build())
        }
        matchingFragment = MatchingFragment()
        homeFragment = HomeFragment()
        messageFragment = MessageFragment()
        mineFragment = MineFragment()

        val fragments = listOf(matchingFragment, homeFragment, messageFragment, mineFragment)
        mBinding.vp.adapter = object : FragmentStateAdapter(this) {
            override fun getItemCount(): Int = fragments.size
            override fun createFragment(index: Int): Fragment = fragments[index]
        }
        mBinding.vp.isUserInputEnabled = false
        mBinding.vp.offscreenPageLimit = 3
        mBinding.vp.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                mBinding.calView.setBackgroundResource(if(position == 0) com.example.resources.R.mipmap.bg_match_back else com.example.resources.R.drawable.male)
                mBinding.vQiu.setVisible(position == 0)
            }

        })

        // 为底部导航栏各个选项添加点击事件
        mBinding.isMatching.setOnClickListener {
            handleBottomNavigationClick(0, mBinding.isMatching, mBinding.isHome, mBinding.isMessage, mBinding.isMine)
        }

        mBinding.isHome.setOnClickListener {
            handleBottomNavigationClick(1, mBinding.isMatching, mBinding.isHome, mBinding.isMessage, mBinding.isMine)
        }

        mBinding.isMessage.setOnClickListener {
            handleBottomNavigationClick(2, mBinding.isMatching, mBinding.isHome, mBinding.isMessage, mBinding.isMine)
        }

        mBinding.isMine.setOnClickListener {
            handleBottomNavigationClick(3, mBinding.isMatching, mBinding.isHome, mBinding.isMessage, mBinding.isMine)
        }
        SocketConnectManager.callLiveData.observe(lifecycleOwner) {
            if (it is Brocast.VideoCallMessage) {
                if (BuildConfig.DEBUG) {
                    showToast("视频来电")
                }
                CallActivity.openActivity(this, CallOperationType.INCOMING_VIDEO, it)
            }

        }
        SocketConnectManager.callVideoLiveData.observe(lifecycleOwner) {
            if (it is CallsPhone) {
                if (BuildConfig.DEBUG) {
                    showToast("拨打电话")
                }
                CallActivity.openActivity(this, CallOperationType.OUTGOING_VIDEO, it)
            }
        }
        Looper.myQueue().addIdleHandler {
            viewModel.getGiftList()
            viewModel.getGiftListApi(GetGiftListRequest.newBuilder().build())
            false
        }

     LiveEventBus.get<Any>(LiveConfig.NET_WORK_MINE).observe(this) {
            if (it is GetAccountInfoReply) {
                UserMKHelper.encode(UserMKHelper.VIP_LEVEL, it.vipLevel)
                homeFragment.initAccount(it)
                matchingFragment.initAccount(it)
            }else if(it is GetGiftListReply){
                it.giftListList.forEach {
                    downloadMp4(it.giftUrl,it.giftName){

                    }

                }

            }
        }
        LiveEventBus.get<Any>(LiveConfig.NET_WORK_GIFT).observe(this) {
            if (it is GetGiftListReply) {
                GetGiftListReplyManager.saveGiftListReply(it)
        }

    }


    }


    // 定义底部导航栏点击事件的处理函数
    private fun handleBottomNavigationClick(viewIndex: Int, vararg imageViews: ImageView) {
        mBinding.vp.setCurrentItem(viewIndex, false)
        when (viewIndex) {
            0 -> {
                matchingDrawable.colorFilter = BlendModeColorFilterCompat.createBlendModeColorFilterCompat(selectColor, BlendModeCompat.SRC_IN)
                mBinding.isMatching.setImageDrawable(matchingDrawable)
                mBinding.isMatching.zoomIn()
            }
            1 -> {
                homeDrawable.colorFilter = BlendModeColorFilterCompat.createBlendModeColorFilterCompat(selectColor, BlendModeCompat.SRC_IN)
                mBinding.isHome.setImageDrawable(homeDrawable)
                mBinding.isHome.zoomIn()
            }
            2 -> {
                messageDrawable.colorFilter = BlendModeColorFilterCompat.createBlendModeColorFilterCompat(selectColor, BlendModeCompat.SRC_IN)
                mBinding.isMessage.setImageDrawable(messageDrawable)
                mBinding.isMessage.zoomIn()
            }
            3 -> {
                mineDrawable.colorFilter = BlendModeColorFilterCompat.createBlendModeColorFilterCompat(selectColor, BlendModeCompat.SRC_IN)
                mBinding.isMine.setImageDrawable(mineDrawable)
                mBinding.isMine.zoomIn()
            }
        }
        if (viewIndex == 1) {
            homeFragment.onRefresh()
        }
        imageViews.forEachIndexed { index, _ ->
            if (viewIndex != index) {
                when (index) {
                    0 -> {
                        matchingDrawable.colorFilter = BlendModeColorFilterCompat.createBlendModeColorFilterCompat(unselectColor, BlendModeCompat.SRC_IN)
                        mBinding.isMatching.setImageDrawable(matchingDrawable)
                        mBinding.isMatching.zoomOut()
                    }
                    1 -> {
                        homeDrawable.colorFilter = BlendModeColorFilterCompat.createBlendModeColorFilterCompat(unselectColor, BlendModeCompat.SRC_IN)
                        mBinding.isHome.setImageDrawable(homeDrawable)
                        mBinding.isHome.zoomOut()
                    }
                    2 -> {
                        messageDrawable.colorFilter = BlendModeColorFilterCompat.createBlendModeColorFilterCompat(unselectColor, BlendModeCompat.SRC_IN)
                        mBinding.isMessage.setImageDrawable(messageDrawable)
                        mBinding.isMessage.zoomOut()
                    }
                    3 -> {
                        mineDrawable.colorFilter = BlendModeColorFilterCompat.createBlendModeColorFilterCompat(unselectColor, BlendModeCompat.SRC_IN)
                        mBinding.isMine.setImageDrawable(mineDrawable)
                        mBinding.isMine.zoomOut()
                    }

                }
            }
        }
    }




    override fun onResume() {
        super.onResume() // sendFirstMessage()
        //  LiveEventBus.get(LiveConfig.NEW_HOME_INDEX).post(mBinding.vp.currentItem)

        if(ChatClient.getInstance().chatManager().unreadMessageCount <= 0){
            mBinding.tvNum.gone()
        }else if(ChatClient.getInstance().chatManager().unreadMessageCount > 99){
            mBinding.tvNum.visible()
            mBinding.tvNum.text = "99+"
        }else{
            mBinding.tvNum.visible()
            mBinding.tvNum.text = ChatClient.getInstance().chatManager().unreadMessageCount.toString()
        }

        viewModel.getUserInfo()
        viewModel.getAccountInfo()

    }


    override fun onStart() {
        super.onStart()

    }

    override fun onStop() {
        super.onStop() // EventBus.getDefault().unregister(this)
    }


    var dialog: CustomDialogFragment? = null
    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.action == KeyEvent.ACTION_DOWN) {
            if (null == dialog) {
                dialog = CustomDialogFragment.newInstance(title = "", content = getString(com.example.resources.R.string.dialog_out_content), positiveButtonText = getString(com.example.resources.R.string.cancel), negativeButtonText = getString(com.example.resources.R.string.yes), listener = object : CustomDialogFragment.DialogClickListener {
                    override fun onPositiveButtonClick() {
                    }

                    override fun onNegativeButtonClick() {
                        moveTaskToBack(true)

                    }
                })
            }
            if (dialog!!.isAdded) {
                dialog?.dismiss()
            } else {
                dialog?.show(supportFragmentManager, "CustomDialog")
            }
        }
        return true
    }


}

